import { useFormMode } from '@/components/base/Form/mode';
import { CodeMirrorJava } from '@/components/business/CodeMirrorJava';
import { MciDialog } from '@/components/base/Dialog';
import { MciButton } from '@/components/base/Button';
import { MciInput, MciLabel } from '@/components/base';
import { conditionsKey } from '../../data';
import { ElTag, ElText, ElTooltip } from 'element-plus';
// import { useClipboard } from '@vueuse/core';
import { VarSearch } from '@/components/business/VarSearch';
import { useDictStore } from '@/store/dict';

export const ExpValue = defineComponent({
  props: {
    condValue: {
      type: String,
      default: ''
    }
  },
  emits: ['value-change'],
  setup(props, { emit }) {
    const formMode = useFormMode();
    const dictStore = useDictStore();
    // const source = ref('');
    // const { copy, isSupported } = useClipboard({ source });
    const { variableOptions } = inject(conditionsKey);
    const variables = ref([]);
    variables.value = variableOptions.variableOptions || [];
    // 代码
    const javaCode = ref(props.condValue);
    const newCode = ref('');
    // 对话框
    const isVisible = ref(false);
    // 组件
    const codeMirrorJavaRef = ref<any>(null);

    // let copyTip = ref('点击复制');
    // const changeCopyTip = (text: string) => {
    //   if (isSupported) {
    //     copy(text);
    //     copyTip.value = '已复制';
    //   } else {
    //     copyTip.value = '不支持';
    //   }
    //   setTimeout(() => {
    //     copyTip.value = '点击复制';
    //   }, 1000);
    // };

    const changeNewCode = (text: string) => {
      let valueStr = '';
      const cursorPos = codeMirrorJavaRef.value?.getCodeMirrorCursor();
      try {
        if (javaCode.value) {
          valueStr = JSON.stringify(javaCode.value, null, '\t');
          const valueArr = JSON.parse(valueStr);
          if (Array.isArray(valueArr)) {
            valueStr = valueArr.join('\n');
          } else {
            valueStr = valueArr;
          }
        }
      } catch (error) {
        console.log(error);
      } finally {
        if (!valueStr) valueStr = javaCode.value;
        if ((cursorPos || cursorPos === 0) && valueStr.length > cursorPos) {
          newCode.value = valueStr.substring(0, cursorPos) + text + valueStr.substring(cursorPos);
        } else {
          newCode.value = valueStr + text;
        }
      }
    };

    // 确定输入
    const confirmHandle = () => {
      let valueStr = '';
      try {
        if (javaCode.value) {
          valueStr = JSON.stringify(javaCode.value, null, '\t');
          const valueArr = JSON.parse(valueStr);
          if (Array.isArray(valueArr)) {
            valueStr = valueArr.join('\n');
          } else {
            valueStr = valueArr;
          }
        }
      } catch (error) {
        console.log(error);
      } finally {
        if (!valueStr) valueStr = javaCode.value;
        emit('value-change', valueStr);
      }
      isVisible.value = false;
    };

    watch(
      () => [props.condValue],
      () => {
        if (props.condValue) {
          javaCode.value = props.condValue;
        } else {
          javaCode.value = '';
        }
      },
      { immediate: true }
    );
    watch(
      () => [variableOptions],
      () => {
        variables.value = variableOptions.variableOptions || [];
      },
      { deep: true }
    );

    return () => {
      return (
        <div class="w-full">
          {formMode?.mode === 'edit' ? (
            <MciInput modelValue={javaCode.value} readonly={true} placeholder="请编辑">
              {{
                append() {
                  return (
                    <ElText
                      onClick={() => {
                        isVisible.value = true;
                        newCode.value = javaCode.value;
                      }}>
                      编辑
                    </ElText>
                  );
                }
              }}
            </MciInput>
          ) : (
            <MciInput modelValue={javaCode.value} readonly={true} />
          )}
          {isVisible.value && (
            <MciDialog
              title={'条件表达式'}
              confirmHandle={confirmHandle}
              modelValue={true}
              width={1000}
              draggable={true}
              customClass="max-height-dialog">
              {{
                default() {
                  return (
                    <div class="flex flex-col">
                      <div>
                        <MciLabel>表达式</MciLabel>
                        <CodeMirrorJava
                          ref={codeMirrorJavaRef}
                          class="mt-16 mx-8"
                          cmHeight={'100px'}
                          code={newCode.value}
                          onUpdate:modelValue={(val: any) => {
                            javaCode.value = val;
                          }}
                        />
                      </div>
                      <div class="w-full mt-8">
                        <MciLabel>函数</MciLabel>
                        <div class="flex flex-wrap py-8 ">
                          {/* <ElTooltip effect="dark" content={'随机数'} placement="top">
                            <ElTag
                              type="info"
                              class={['cursor-pointer', 'mx-4', 'my-4']}
                              onClick={() => changeNewCode(`F.randInt()`)}>
                              F.randInt(a)
                            </ElTag>
                          </ElTooltip>
                          <ElTooltip effect="dark" content={'最小值'} placement="top">
                            <ElTag
                              type="info"
                              class={['cursor-pointer', 'mx-4', 'my-4']}
                              onClick={() => changeNewCode(`F.min()`)}>
                              F.min(a,b)
                            </ElTag>
                          </ElTooltip>
                          <ElTooltip effect="dark" content={'最大值'} placement="top">
                            <ElTag
                              type="info"
                              class={['cursor-pointer', 'mx-4', 'my-4']}
                              onClick={() => changeNewCode(`F.max()`)}>
                              F.max(a,b)
                            </ElTag>
                          </ElTooltip> */}
                          {dictStore.dictExpFunc?.map((item: string) => {
                            return (
                              <>
                                <ElTag
                                  type="info"
                                  class={['cursor-pointer', 'mx-4', 'my-4']}
                                  onClick={() => {
                                    changeNewCode(item);
                                  }}>
                                  {item}
                                </ElTag>
                              </>
                            );
                          })}
                        </div>
                      </div>
                      {variables.value && variables.value.length > 0 && (
                        <div>
                          <MciLabel>变量</MciLabel>
                          <div class="flex flex-wrap mt-16 px-8">
                            <VarSearch
                              variables={variables.value}
                              onVar={(v: string) => {
                                changeNewCode(v);
                              }}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  );
                },
                footer() {
                  return (
                    <>
                      <MciButton onClick={() => (isVisible.value = false)}>取消</MciButton>
                      <MciButton type="primary" onClick={confirmHandle}>
                        确定
                      </MciButton>
                    </>
                  );
                }
              }}
            </MciDialog>
          )}
        </div>
      );
    };
  }
});
